/*
 * Copyright 2007 Peter Zelenay.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *     
*/
package net.zelenay.jcrviewer.control;

import javax.jcr.LoginException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import net.zelenay.jcrviewer.data.JackrabbitRepositoryProvider;
import net.zelenay.jcrviewer.view.ViewerPanel;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public abstract class AbstractRepositoryController implements RepositoryController {
	
	private String viewerContext;
	
	private Repository repository = null;
	
	private String repoHome; 
	
	private String repoConfig;
	
	private ClassPathXmlApplicationContext innerCtx;
	
	private Session session;

	/* (non-Javadoc)
	 * @see net.zelenay.jcrviewer.control.RepositoryController#getViewFrame()
	 */
	@Override
	public ViewerPanel getViewPanel() throws LoginException, RepositoryException {
		session =  initRepository().login();
		innerCtx = new ClassPathXmlApplicationContext(getViewerContext());
		ViewerPanel fr = (ViewerPanel) innerCtx.getBean("view");
		fr.setName(session.getUserID() + "@" + session.getWorkspace().getName());
		fr.setToolTipText(repoHome);
		fr.setSession(session);
		return fr;
	}
	
	

	@Override
	public void close() {
		session.logout();
		innerCtx.close();
	}



	protected abstract String[] getConfig();
	
	/**
	 * @return the viewerContext
	 */
	public String getViewerContext() {
		return viewerContext;
	}

	/**
	 * @param viewerContext the viewerContext to set
	 */
	public void setViewerContext(String viewerContext) {
		this.viewerContext = viewerContext;
	}

	private synchronized Repository initRepository() {
		if(repository == null) {
			String[] conf = getConfig();
			repoConfig = conf[0];
			repoHome = conf[1];
			repository = JackrabbitRepositoryProvider.getRepository(repoConfig, repoHome);
		}
		return repository;
	}
}
